package base_05_reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

/**
 * 反射之Constructor类
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/24 17:48
 */
public class ConstructorDemo {
    private String name;

    ConstructorDemo() {
        System.out.println(">>>>非public构造器");
    }

    public ConstructorDemo(String name) {
        this.name = name;
    }

    public ConstructorDemo(String name, Integer n) {
        this.name = name;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<ConstructorDemo> clazz = ConstructorDemo.class;
        //获取所有public构造器类
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> con : constructors) {
            System.out.println(con.getName());
        }
        //获取非public构造器类
        System.out.println(">>>>>>>>>>getDeclaredConstructor>>>>>>>>>>");
        Constructor<ConstructorDemo> constructor1 = clazz.getDeclaredConstructor();
        ConstructorDemo instance = constructor1.newInstance();
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();

        //通过构造器方法形参类型获取构造器类
        System.out.println(">>>>>>>>>>getConstructor>>>>>>>>>>");
        Constructor<ConstructorDemo> constructor2 = clazz.getConstructor(String.class, Integer.class);
        System.out.println("constructor2 name>>>" + constructor2.getName());
        System.out.println("toGenericString>>" + constructor2.toGenericString());
        try {
            ConstructorDemo constructorDemo = constructor2.newInstance("ss", 11);
            System.out.println(constructorDemo.name);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        //获取构造器形参数组
        System.out.println(">>>>>>>>>>getParameters>>>>>>>>>>");
        Parameter[] parameters = constructor2.getParameters();
        for (Parameter parameter : parameters) {
            System.out.print("parameter name>>>" + parameter.getName());
            System.out.println(parameter.getType());
        }
        //构造器形参类型class
        System.out.println(">>>>>>>>>>getParameterTypes>>>>>>>>>>");
        Class<?>[] types = constructor2.getParameterTypes();
        for (Class<?> type : types) {
            System.out.println(type.getSimpleName() + ">>type name>>" + type.getName());
        }
        System.out.println("=============基本类型也有Class对象=================");
        Class<Integer> integerClass = int.class;
    }
}
